import { Component, OnInit } from '@angular/core';
import { AlertController } from '@ionic/angular';
import { pull } from 'lodash-es';
import { CallService } from '../call.service';

@Component({
  selector: 'app-config',
  templateUrl: './config.page.html',
  styleUrls: ['./config.page.scss'],
})
export class ConfigPage implements OnInit {
  config = {
    dataBasePath: '/home/ender/.se',
    deploy: false,
    exts: ['.go', '.txt', '.puml', '.java', '.ts'],
    height: 800,
    ignore: ['vendor', 'target', 'node_modules', '.git'],
    limit: 100,
    offset: 0,
    width: 1000,
  };
  constructor(
    private callService: CallService,
    private alertCtrl: AlertController,
  ) { }

  async ngOnInit() {
    this.config = await this.callService.call('getConfig', { def: this.config });
  }

  async save() {
    await this.callService.call('setConfig', { msg: '保存中...' }, this.config);
  }

  addExt() {
    this.addItem('新增扩展文件名', '请输入要索引的扩展文件名', (data: any) => {
      if (!data.str) { return; }

      const ext = data.str[0] !== '.' ? `.${data.str}` : data.str;

      if (this.config.exts.includes(ext)) { return; }

      this.config.exts.push(ext);
      this.save();
    });
  }

  addIgnore() {
    this.addItem('新增忽略目录', '请输入不要索引的目录名', (data: any) => {
      if (!data.str || this.config.ignore.includes(data.str)) { return; }

      this.config.ignore.push(data.str);
      this.save();
    });
  }

  delExt(ext: string) {
    this.delItem(`是否删除扩展文件名: ${ext}?`, () => {
      pull(this.config.exts, ext);
      this.save();
    });
  }

  delIgnore(ignore: string) {
    this.delItem(`是否删除忽略目录: ${ignore}?`, () => {
      pull(this.config.ignore, ignore);
      this.save();
    });
  }

  async delItem(msg: string, handler: (data: any) => void) {
    const alert = await this.alertCtrl.create({
      header: '是否删除？',
      message: msg,
      buttons: [
        {
          text: '取消',
          role: 'cancel',
          cssClass: 'secondary',
        }, {
          text: '确定',
          handler,
        }
      ]
    });

    await alert.present();
  }

  async addItem(msg: string, placeholder: string, handler: (data: any) => void) {
    const alert = await this.alertCtrl.create({
      header: '新增',
      message: msg,
      inputs: [
        {
          placeholder,
          name: 'str',
          type: 'text',
        },
      ],
      buttons: [
        {
          text: '取消',
          role: 'cancel',
          cssClass: 'secondary',
        }, {
          text: '确定',
          handler,
        }
      ]
    });

    await alert.present();
  }
}
